﻿using AIPlugin.Configuration;
using AIPlugin.Fetures;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using OpenAI.Chat;
using System;
using System.ClientModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AIPlugin.Core.Extensions
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddAIPlugin(this IServiceCollection services, Action<ChatOptions> configure)
        {
            services.Configure(configure);

            services.AddAICore(configure)
                    .AddCodeAssistant();

            return services;
        }

        /// <summary>
        /// 插件核心功能
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private static IServiceCollection AddAICore(this IServiceCollection services, Action<ChatOptions> configure)
        {
            var opt = new ChatOptions();
            configure.Invoke(opt);
            var credential = new ApiKeyCredential(opt.Secret);
            var endpoint = new Uri(opt.Endpoint);
            var client = new ChatClient(opt.Model, credential, new OpenAI.OpenAIClientOptions
            {
                Endpoint = endpoint
            });
            services.AddScoped(s => client);
            services.AddScoped<AIClient>();
            return services;
        }

        /// <summary>
        /// 添加代码助手
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private static IServiceCollection AddCodeAssistant(this IServiceCollection services)
        {
            services.AddScoped<CodeAssistantService>();
            return services;
        }
    }
}
